#include "stm32f10x.h"                  // Device header
#include "Timer.h"
#include "Delay.h"
#include "OLED.h"
#include "Servo.h"
#include "Hcsro4.h"
#include "Key.h"
#include "Num_Len.h"
//#include "JDY31.h"
#include "USART.h"
#include "string.h"

#define ON	120
#define OFF	0

//uint8_t arr[4] = {0x42, 0x43, 0x44, 0x45};
//uint8_t RxData;

uint8_t KeyNum = 0;
float Angel = 0;
uint8_t Flag = 1;

int main(void)
{
	Servo_Init();
	Timer_Init();
	Hcsro4_Init();
	OLED_Init();
	Key_Init();
	My_USART_Init();
	
	Servo_SetAngle(0);
	uint32_t Distance_mm = 0;
	uint32_t Distance_m = 0;
	uint32_t Distance_m_p = 0;
	
	OLED_ShowString(1,1,"Distance:");
	OLED_ShowString(4,1,"State:");
	
	while (1)
	{
		KeyNum = Key_GetNum();
		
		if (KeyNum == 1)
		{
			Angel += 120;
			if(Angel >= 180)
			{
				Angel = 0;
			}
			if(Angel == 120)
			{
				Servo_SetAngle(Angel);
				OLED_ShowString(4,7,"         ");
				OLED_ShowString(4,7,"Servo_ON");
				Flag = 0;
			}
			else
			{
				Servo_SetAngle(Angel);
				OLED_ShowString(4,7,"Servo_OFF");
				Flag = 1;
			}
		}
		
		if (USART_Flag == 1)
		{
			if (strcmp(USART_ReceivePacket, "Servo_ON") == 0)
			{
				Servo_SetAngle(120);
				OLED_ShowString(4,7,"         ");
				OLED_ShowString(4,7,"Servo_ON");
				Delay_ms(1000);
				Flag = 0;
			}
			else if (strcmp(USART_ReceivePacket, "Servo_OFF") == 0)
			{
				Servo_SetAngle(0);
				OLED_ShowString(4,7,"Servo_OFF");
				Flag = 1;
			}
			USART_Flag = 0;
		}
		else if (Flag == 1)
		{
			if(Distance_mm<=200&&Distance_mm>0)
			{
				Angel = 120;
				Servo_SetAngle(Angel);
				OLED_ShowString(4,7,"         ");
				OLED_ShowString(4,7,"Servo_ON");
				Delay_ms(1000);
			}
			if(Distance_mm > 500 || Distance_mm == 0)
			{
				Angel = 0;
				Servo_SetAngle(Angel);
				OLED_ShowString(4,7,"Servo_OFF");
			}
		}
			
		
		
		
		Distance_mm = Hcsro4_Get_mm();
		Distance_m = Distance_mm/1000;
		Distance_m_p = Distance_mm%1000;
		
		OLED_Clear_Part(2,1,16);
		OLED_ShowNum(2, 1, Distance_m, Num_Get_Len(Distance_m));
		OLED_ShowChar(2, Num_Get_Len(Distance_m)+1, '.');
		if (Distance_m_p < 100)
		{
			OLED_ShowNum(2, Num_Get_Len(Distance_m)+1+1, 0, 1);
			OLED_ShowNum(2, Num_Get_Len(Distance_m)+1+1+1, Distance_m_p, Num_Get_Len(Distance_m_p));
			OLED_ShowChar(2, Num_Get_Len(Distance_m)+1+1+1+Num_Get_Len(Distance_m_p), 'm');
		}
		else
		{
			OLED_ShowNum(2, Num_Get_Len(Distance_m)+1+1, Distance_m_p,  Num_Get_Len(Distance_m_p));
			OLED_ShowChar(2, Num_Get_Len(Distance_m)+1+1+Num_Get_Len(Distance_m_p), 'm');
		}
		OLED_Clear_Part(3,1,16);
		OLED_ShowNum(3, 1, Distance_mm, Num_Get_Len(Distance_mm));
		OLED_ShowString(3, Num_Get_Len(Distance_mm)+1, "mm");
	}
}
